package com.demo.controller;

import com.demo.response.Resp;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @author zhiqiang
 */
@Slf4j
@RestController
@RequestMapping("/httpClientController")
public class HttpClientController {
    @Autowired
    private HttpClient httpClient;

    @GetMapping("/test1")
    public Resp buildStudent1() throws IOException {
        HttpGet httpGet = new HttpGet("http://localhost:9999/ok/testController/test1/1/张三");
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            log.error("请求错误，请求地址【{}】", httpGet.getURI(), e);
        }
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);

//        String string = entity.toString();
//        Class clazz = Class.forName(string);
//        Student student = (Student) clazz.newInstance();
        return Resp.ok(result);
    }


    @PostMapping("/test2")
    public Resp buildStudent2() throws IOException {
        HttpPost httpPost = new HttpPost("http://localhost:9999/ok/testController/test2?name=张三");
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            log.error("请求错误，请求地址【{}】", httpPost.getURI(), e);
        }
        HttpEntity entity1 = response.getEntity();
        String result = EntityUtils.toString(entity1);
        return Resp.ok(result);
    }
}
